package com.cyh.web.controller;

import com.cyh.core.framework.annotation.OperationLogDetail;
import com.cyh.core.framework.annotation.RoleToken;
import com.cyh.core.framework.common.constant.FileConstant;
import com.cyh.core.framework.domain.dto.ResultDTO;
import com.cyh.core.framework.common.utils.FileUtil;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.*;
import java.net.URLEncoder;

@RestController
@RequestMapping("/file")
public class FileController {

    @RoleToken(Roleid = {0,1,2})
    @PostMapping("/upload")
    @OperationLogDetail
    public ResultDTO UploadFile(@NotNull MultipartFile upFile) throws IOException {
        if(!upFile.isEmpty()) {
            String originalFilename = upFile.getOriginalFilename();
            String filePath = FileConstant.UPLOAD_FILE_PATH + "/" + System.currentTimeMillis() + "_" + originalFilename;
            String realPath = FileUtil.getRealPath(filePath);
            System.out.println(realPath);
            File file = new File(realPath);
            upFile.transferTo(file);
            return ResultDTO.Success("上传成功! "+filePath,1);
        }else {
            return ResultDTO.Failure(403,"上传为空");
        }
    }

    @RoleToken(Roleid = {0,1,2})
    @GetMapping("/download/{fileName}")
    @OperationLogDetail
    public ResultDTO downloadFile(@PathVariable @NotNull String fileName, HttpServletResponse response){

        File df=new File(FileUtil.getRealPath(FileConstant.UPLOAD_FILE_PATH+"/"+fileName));
        if(!df.exists()||!df.isFile()){
            return ResultDTO.Failure(404,"下载失败 文件不存在");
        }

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        // 下载文件能正常显示中文
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        byte[] buff = new byte[1024];
        //创建缓冲输入流
        BufferedInputStream bis = null;
        OutputStream outputStream = null;

        try {
            outputStream = response.getOutputStream();

            //这个路径为待下载文件的路径

            bis = new BufferedInputStream(new FileInputStream(df));
            int read = bis.read(buff);

            //通过while循环写入到指定了的文件夹中
            while (read != -1) {
                outputStream.write(buff, 0, buff.length);
                outputStream.flush();
                read = bis.read(buff);
            }
        } catch ( IOException e ) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return ResultDTO.Success("下载完成",1);
    }

}
